package com.itheima.nio.buffer.demo05;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServerDemo05 {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //
        serverSocketChannel.socket().bind(new InetSocketAddress(7878));
        serverSocketChannel.configureBlocking(false);
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null){
                socketChannel.configureBlocking(false);
                ByteBuffer byteBuffer = ByteBuffer.allocate(4);
                int read = socketChannel.read(byteBuffer);
                while (read > 0){
                    byteBuffer.flip();
                    byte[] bytes = byteBuffer.array();
                    System.out.println(new String(bytes, 0, read));
                    byteBuffer.clear();
                    read = socketChannel.read(byteBuffer);
                }
//                byteBuffer.flip();
//                byte[] bytes = byteBuffer.array();
//                System.out.println(new String(bytes, 0, read));
//                byteBuffer.clear();
//
//                read = socketChannel.read(byteBuffer);
//                byteBuffer.flip();
//                bytes = byteBuffer.array();
//                System.out.println(new String(bytes, 0, read));
//                byteBuffer.clear();
//
//                read = socketChannel.read(byteBuffer);
//                System.out.println(read);
//
//                read = socketChannel.read(byteBuffer);
//                System.out.println(read);

                socketChannel.close();
            }
        }
    }
}
